import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ModalController, ViewController } from 'ionic-angular';
import { StorageProvider } from '../../providers/storage/storage';
import { HttpProvider } from '../../providers/http/http';
import { DialogProvider } from '../../providers/dialog/dialog';
import { UserInfoProvider } from '../../providers/user-info/user-info';
import { BleProvider } from '../../providers/ble/ble';
import { OrderDataService } from '../../providers/service/order-data.service';
import { UserDataService } from '../../providers/service/user-data.service';
import { Network } from '@ionic-native/network';
import { LoadingController, Loading } from 'ionic-angular';
import { WechatProvider } from '../../providers/wechat/wechat';
declare let cordova: any;
// declare let Wechat: any;
/**
 * Generated class for the ToPayPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-to-pay',
  templateUrl: 'to-pay.html',
})
export class ToPayPage {

  // 选中价格
  charge_uprice: Charge_uprice_List = new Charge_uprice_List();

  // 设备id
  power_unit_id: any;

  // 用户信息
  userInfo: login_info = new login_info();

  // 1小时 = 3600时间搓;
  timeRubbing = 3600;

  // 支付类型
  paytype = '4';

  //有网状态=1 断网=0
  Internet = 1;

	public Coupons: Coupons[] = new Array<Coupons>();

  // 优惠券信息
  public coupons: Ma_coupon = {
    coupon_id: '',
    coupon_type: '',
    coupon_name: '',
    denomination: 0,
    stock: '',
    expiry_date: '',
    is_issuance: '',
    created_at: '',
    updated_at: '',
    cuser_id: '',
    uuser_id: '',
    is_del: '',
  };

  constructor(
    public navCtrl: NavController,
    public viewCtrl: ViewController,
    public navParams: NavParams,
    public storage: StorageProvider,
    public http: HttpProvider,
    public dialog: DialogProvider,
    public user: UserInfoProvider,
    public order: OrderDataService,
    private network: Network,
    public ble: BleProvider,
    public modalCtrl: ModalController,
    public userData: UserDataService,
    public loadingCtrl: LoadingController,
    public wx: WechatProvider) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ToPayPage');
    this.charge_uprice = this.navParams.get('charge_uprice');
    this.charge_uprice.unit_price = Math.round(parseFloat(this.charge_uprice.unit_price) * 100) / 100;
    this.power_unit_id = this.navParams.get('power_unit_id');

    this.userInfo = this.user.getuserInfo();
    // this.storage.getStorage("login_info").then(res => {
    //   console.log(res);
    //   if (res != undefined) {
    //     this.userInfo = res;
    //   }
    // });
    
    this.getCoupons();
  }

  ionViewDidLeave() {
    // if (this.ble.device_state === 'on') {
    // this.ble.disconect();
    //   this.ble.device_state = 'off';
    // }

  }
  ionViewWillEnter() {
    // let _this = this;
    // let a = setInterval(
    //   function () {
    //       _this.ble.write0110();
    //       clearInterval(a);
    //   }, 500)
    if (this.network.type === 'none' || this.network.type === '2g') {
      this.Internet = 0;
    }
    // this.ble.write0110();

  }
  
  getCoupons() {
    var timestamp = Math.ceil(new Date().getTime()/1000);
    this.http.postJson('', 'member/memberco/index?page=1', {
      "where": ['and', ["=", "member_id", this.userInfo.member_id], ["=", "is_use", '0'],[">=","overdue_time",timestamp]],
      "limit": 15,
      "joinwith": ["ma_coupon"]
    }, '').then(res => {
      console.log(res)
      if (res['status'] == 200) {
        this.getMessage(res['data']);
      }
    });
  }


  getMessage(Coupons) {
    this.Coupons.splice(0);
    console.log(Coupons);
    for (let coupons of Coupons) {
      if (coupons.ma_coupon) {
        coupons.ma_coupon.expiry_date = (parseInt(coupons.created_at) + parseInt(coupons.ma_coupon.expiry_date) * 24 * 60 * 60) * 1000;//券有效期
        if (new Date().getTime() < coupons.ma_coupon.expiry_date) {
          this.Coupons.push(coupons);
          console.log(this.Coupons[0]);
  		  this.coupons =this.Coupons[0].ma_coupon;
  		  console.log(this.coupons);
  		  return false;
        }
      }
    }
  }
  
  /**
   * 支付
   */
  async create() {

    let loading = this.loadingCtrl.create({
      content: '支付中...'
    });
    loading.present();
   
    let ntime = new Date();
    let stime = parseFloat(ntime.getTime().toString().slice(0, 10));
    let etime = parseFloat(ntime.getTime().toString().slice(0, 10)) + (this.timeRubbing * this.charge_uprice.charge_time);
    let a;

    if (this.coupons.coupon_id !== '') {
      a = {
        charge_time_start: stime,
        charge_time_end: etime,
        charge_time: this.charge_uprice.charge_time.toString(),
        power_unit_id: this.power_unit_id,
        member_id: this.userInfo.member_id,
        payment_money: 0,
        discount_money: this.coupons.denomination > this.charge_uprice.unit_price ? this.charge_uprice.unit_price : this.coupons.denomination,
        refund_money: 0.00,
        order_money: this.charge_uprice.unit_price,
        payment_id: this.paytype,//'支付方式id 1微信，2支付宝 3离线 4余额'
        states: 0,
        upload: 0, //是否已经上传服务器 0没有 1上传
        coupon_id: this.coupons.coupon_id
      }

    } else {
      a = {
        charge_time_start: stime,
        charge_time_end: etime,
        charge_time: this.charge_uprice.charge_time.toString(),
        power_unit_id: this.power_unit_id,
        member_id: this.userInfo.member_id,
        payment_money: 0,
        discount_money: 0.00,
        refund_money: 0.00,
        order_money: this.charge_uprice.unit_price,
        payment_id: this.paytype,//'支付方式id 1微信，2支付宝 3离线 4余额'
        states: 0,
        upload: 0, //是否已经上传服务器 0没有 1上传
        coupon_id: ''
      }
    }

    // 断网情况
    if (this.network.type === 'none' || this.network.type === '2g') {
      a.payment_id = '3';
      if (this.userInfo.local_balance < a.order_money) {
        this.dialog.showAlert('本地余额不足', '');
        loading.dismiss();
        return;
      }
      this.order.save(a);
      //    this.userInfo.local_balance = Math.round((this.userInfo.local_balance - a.order_money) * 100) / 100;
      this.userInfo.local_balance = (this.userInfo.local_balance - a.order_money).toFixed(2);
      // this.dialog.showAlert('userInfo', JSON.stringify(this.userInfo));
      this.userData.save(this.userInfo);
      // this.dialog.showAlert('支付成功', '');
      this.dischargeApplication(ntime);

      //   const index = this.viewCtrl.index;
      // for(let i = index; i > 0; i--){
      //         this.navCtrl.remove(i);
      //   }
      // this.navCtrl.parent.select(2);
      this.navCtrl.popToRoot();
      //    this.navCtrl.setRoot('CenterPage');

      loading.dismiss();
      return;
    }

    // 联网情况
    if (this.network.type !== 'none' && this.network.type !== '2g') {
      if ((this.userInfo.balance < (a.order_money - a.discount_money) && a.payment_id === '4')) {
        this.dialog.showAlert('余额不足', '');
        loading.dismiss();
        return;
      }
      
      const res = await this.http.postJson('', 'member/memberch/create', a, '')
        .then(res => {
          loading.dismiss();
          if (res['status'] == 200) {         
            if ((a.order_money - a.discount_money) <= 0) {
              this.login().then((res) => {
                this.dischargeApplication(ntime);

                // const index = this.viewCtrl.index;
                // for(let i = index; i > 0; i--){
                //             this.navCtrl.remove(i);
                //         }
                // this.navCtrl.parent.select(2);
                this.navCtrl.popToRoot();
                //              this.navCtrl.setRoot('CenterPage');
              });
              // this.dialog.showAlert('支付成功', '');
            } else if (a.payment_id === '2') {
              const ali = res['data'][0];
              this.alipay(ali.date, ntime, ali.out_trade_no);
            } else if (a.payment_id === '1') {
              const wx = res['data'][0];
              this.wechat(wx.date, ntime, wx.out_trade_no);
            } else {
              this.login().then((res) => {
                this.dischargeApplication(ntime);

                // const index = this.viewCtrl.index;
                // for(let i = index; i > 0; i--){
                //             this.navCtrl.remove(i);
                //         }
                // this.navCtrl.parent.select(2);
                this.navCtrl.popToRoot();
                //              this.navCtrl.setRoot('CenterPage');
              });
              //               this.dialog.showAlert('支付成功', '');
            }
          } else {
            this.dialog.showAlert(res['message'], '');
          }
        });
    }
  }

  /**
   * 获取用户信息
   */
  async login() {
    //   await this.storage.getStorage("login_info").then(res => {
    // 	if(res != undefined) {
    // 		this.userInfo = res;
    // 	}
    // });;
    // console.log(this.userInfo);
    const res = await this.http.postJson('', 'member/member/view?id=' + this.userInfo.member_id, {}, '')
      .then(res => {
        console.log(res)
        if (res['status'] == 200) {
          res['data']['password'] = this.userInfo.password;
          res['data']['isAutomaticLogon'] = this.userInfo.isAutomaticLogon;
          this.userInfo = res['data'];
          this.user.setuserInfo(this.userInfo);
          // this.storage.saveStorage("login_info", res['data']);
          // this.http.setAuthorization(res['data']['access_token']);//该令牌唯一表示该用户、用户的组和用户的特权。系统使用令牌控制用户可以访问哪些安全对象，并控制用户执行相关系统操作的能力
          // this.navCtrl.push('CenterPage');
        }
      });
  }

  // 优惠券
  openData_statistics() {
    if (this.network.type === 'none' || this.network.type === '2g') {
      this.dialog.showAlert('提示', '断网情况下无法使用优惠券');
    } else {
      let modal = this.modalCtrl.create('PayMyCouponsPage', {});
      modal.onDidDismiss(data => {
        if (data) {
          this.coupons = data.data;
        } else {
          this.coupons = {
            coupon_id: '',
            coupon_type: '',
            coupon_name: '',
            denomination: 0,
            stock: '',
            expiry_date: '',
            is_issuance: '',
            created_at: '',
            updated_at: '',
            cuser_id: '',
            uuser_id: '',
            is_del: '',
          };
        }
      });
      modal.present();
    }
  }

  /**
   * 支付宝支付
   */
  async alipay(payInfo, ntime, out_trade_no) {
    cordova.plugins.alipay.payment(payInfo,
      (success) => {

        this.login();
        this.dischargeApplication(ntime);

        // const index = this.viewCtrl.index;
        // for(let i = index; i > 0; i--){
        //             this.navCtrl.remove(i);
        //         }
        // this.navCtrl.parent.select(2);
        this.navCtrl.popToRoot();
        //      this.navCtrl.setRoot('CenterPage');
        // this.dialog.showAlert('支付成功', '');
      },
      (error) => {
        //      this.dialog.showAlert('支付失败', '');
        this.http.postJson('', 'apis/apis/couponpay' , {'out_trade_no': out_trade_no}, '').then(res => {});
      });
    return;
  }

  async wechat(payInfo, ntime, out_trade_no) {
    let params = {
      mch_id: payInfo.partnerid, // merchant id
      prepay_id: payInfo.prepayid, // prepay id
      nonce: payInfo.noncestr, // nonce
      timestamp: payInfo.timestamp + "", // timestamp
      sign: payInfo.sign, // signed string
      appid: 'wx541309d09585de38'
    };
    // this.dialog.showAlert('params', JSON.stringify(params));
    // Wechat.sendPaymentRequest(params,
    //   (success) => {

    //     this.login();
    //     this.dischargeApplication(ntime);

        // const index = this.viewCtrl.index;
        // for(let i = index; i > 0; i--){
        //             this.navCtrl.remove(i);
        //         }
        // this.navCtrl.parent.select(2);
        // this.navCtrl.popToRoot();
        //      this.navCtrl.setRoot('CenterPage');
        // this.dialog.showAlert('支付成功', '');
      // },
      // (error) => {
        //      this.dialog.showAlert('支付失败', '');
      // });

      this.wx.sendPaymentRequest(params).then((res) => {
        this.login();
        this.dischargeApplication(ntime);
        this.navCtrl.popToRoot();
      }, (error) => {
        //  this.dialog.showAlert('支付失败', error);
        this.http.postJson('', 'apis/apis/couponpay' , {'out_trade_no': out_trade_no}, '').then(res => {});
      });
    return;

  }

  /**
   * 放电申请
   */
  dischargeApplication(ntime: Date) {
    let head = {
      bHeadMark: 'LKB', //3字节 要经过ASCII码转换
      bVer: 1, //1字节
      bLength: 24, //2字节
      bCmdld: '0200', //2字节
      bSeq: 0, //2字节
      bCks: 1111 //2字节
    }

    let headBuffer = this.ble.assembleHeadBuffer(head.bHeadMark, head.bVer, head.bLength, head.bCmdld, head.bSeq, head.bCks);
    let write = {
      member_id: this.supplementZer0((this.user.userInfo.member_id).toString(), 4),
      charge_time: this.supplementZer0((this.charge_uprice.charge_time * 60).toString(16), 2)
    }
    let data = [write.member_id, write.charge_time];
    let str = this.ble.ling(data);
    let year = this.supplementZer0(parseInt(ntime.getFullYear().toString().slice(2, 4)).toString(16), 1) + this.supplementZer0((ntime.getMonth() + 1).toString(16), 1) + this.supplementZer0((ntime.getDate()).toString(16), 1) + this.supplementZer0((ntime.getHours()).toString(16), 1) + this.supplementZer0((ntime.getMinutes().toString(16)), 1) + this.supplementZer0((ntime.getSeconds().toString(16)), 1);
    str = year + str;
    this.ble.write0020(headBuffer, str)
  }
  
//payExplain(){
//	this.dialog.showAlert('支付说明……', '');
//}


  /**
 * 用0补充位数
 * @param str 
 * @param num 
 */
  supplementZer0(str: String, num: number): any {
    var pos = 0;
    num *= 2;
    var len = str.length;

    if (len !== num) {
      for (let i = 0; i < num - len; i++) {
        str = '0' + str;
      }
    }
    return str;
  }

}
export class Charge_uprice_List {
  id: any; // 排序
  charge_time: number; // 时长
  unit_price: any; // 价格
}

export class login_info {
  member_id: any;
  nickname: any;
  phone: any;
  balance: any;
  local_balance: any;
  member_state: any;
  created_at: any;
  updated_at: any;
  cuser_id: any;
  uuser_id: any;
  is_del: any;
  password: any;
  file_type_id: any;
  access_token: any;
  isAutomaticLogon: any;
}

export class Ma_coupon {
  coupon_id: any;
  coupon_type: any;
  coupon_name: any;
  denomination: any;
  stock: any;
  expiry_date: any;
  is_issuance: any;
  created_at: any;
  updated_at: any;
  cuser_id: any;
  uuser_id: any;
  is_del: any;
}

export class Coupons {
  member_coupon_id: any;
  member_id: any;
  coupon_id: any;
  created_at: any;
  updated_at: any;
  cuser_id: any;
  uuser_id: any;
  is_use: any;
  use_coupon_tiem: any;
  remarks: any;
  ma_coupon: {
    coupon_id: any;
    coupon_type: any;
    coupon_name: any;
    denomination: any;
    stock: any;
    expiry_date: any;
    is_issuance: any;
    created_at: any;
    updated_at: any;
    cuser_id: any;
    uuser_id: any;
    is_del: any;
  }

}